<!DOCTYPE html>
<html lang=''>

<head>
    <meta charset='UTF-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Document</title>
    <script src='./vue.js'></script>
    <style>
        .box {
            border: 1px solid #f66;
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <div id='app'>
        <h1> 总值： {{ total }} </h1>
        <!-- 2. 监听自定义事件 -->
        <!-- 子组件会触发 calc 事件后，然后执行回调函数 received -->
        <counter @calc="received" @changename="changeName"></counter>
        <counter @calc="received"></counter>
        <counter @calc="received"></counter>
    </div>
</body>
<template id="counter">
    <div class="box">
        <p>counter : {{ counter }}</p>
        <button @click="add">增加</button>
        <button @click="reduce">减少</button>
    </div>
</template>

<script>
    const app = Vue.createApp({
        data () {
            return {
                total: 0
            }
        },
        methods: {
            // 1. 有接收子组件传递参数的方法
            received (value) {
                console.log(value);
                this.total += value
            },
            changeName (val) {
                console.log('接收name:' + val);
            }
        }
    })
    app.component('counter', {
        template: '#counter',
        data () {
            return {
                counter: 0
            }
        },
        methods: {
            add () {
                const ran = Math.round(Math.random() * 10)
                this.counter += ran

                // 3. 用来触发自定义事件的方法，并且将参数传递过去
                this.$emit('calc', ran)

                this.$emit('changename', '张一')
            },
            reduce () {
                let ran = Math.round(Math.random() * 10)
                if (ran > this.counter) {
                    ran = this.counter
                }
                this.counter -= ran
                this.$emit('calc', -ran)
            }
        },
        props: {

        }
    })

    app.mount('#app')
</script>

</html>